package com.herr.springboot.data.mongo.controller;

import com.herr.springboot.data.mongo.dao.UserDao;
import com.herr.springboot.data.mongo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 *
 show databases
 use test
 show collections
 db.createCollection("user")
 db.user.insert({name: 'iherr', age: 18});
 db.user.find()
 * @author herr05
 */

@RestController
/**
 * 由于使用了Spring Data JPA，可直接访问/user，/user/id等路径
 */
@RequestMapping("/mongo")
public class TestController {

    @Autowired
    UserDao userDao;

    @Autowired
    MongoTemplate mongoTemplate;

    @RequestMapping("/set")
    public String set(){
        User user=new User("iherr","19");
        userDao.insert(user);
        return "success";
    }

    @GetMapping("/findAll")
    public List<User> findAll(){

        return userDao.findAll();
    }

    @GetMapping("/delete")
    public String delete(String id){
        userDao.deleteById(id);
        return "success";
    }

    @GetMapping("/findById")
    public User findById(String id){
        Optional<User> user = userDao.findById(id);
        if (user.isPresent())
            return user.get();
        else {
            return new User();
        }
    }

    @GetMapping("/findAll2")
    public List<User> findAll2(){

        List<User> list = mongoTemplate.findAll(User.class);
        return list;
    }

}
